package com.byzk.p2p.admin.fuiou.service;

import java.util.Date;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.CancelService;
import com.byzk.p2p.admin.borrow.vo.BorrowVo;
import com.byzk.p2p.admin.borrow.vo.UserTenderVo;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.PreAuthCancel;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.service.UserService;

@Service
public class PreAuthCancelService {

	@Autowired
	private BorrowService borrowService;
	@Autowired
	private UserService userService;
	@Autowired
	private CallbackService callbackService;
	@Autowired
	private CancelService cancelService;

	public boolean preAuthCancel(int borrowId, UserTenderVo tenderVo) {
		boolean result=false;
		BorrowVo vo = borrowService.detailBorrowVo(borrowId);
		User tenderUser = userService.getById(tenderVo.getUserId());
		User borrowUser = userService.getById(vo.getBorrowUserId());

		PreAuthCancel auth = new PreAuthCancel();
		auth.setMchnt_cd(Config.mchnt_cd);
		auth.setMchnt_txn_ssn(DateUtils.getFullFormat() + (new Random().nextInt(8999) + 1000));
		auth.setOut_cust_no(tenderUser.getPhone());
		auth.setIn_cust_no(borrowUser.getPhone());
		auth.setContract_no(tenderVo.getContractNo());
		auth.setRem("");
		String inputStr = auth.regSignVal();
		auth.setSignature(SecurityUtils.sign(inputStr));

		System.out.println("----明文参数：" + inputStr);

		String backStr = "";
		try {
			backStr = WebUtils.sendHttp(Config.pre_auth_cancel_url, auth);

			System.out.println("-------回调结果:" + backStr);

			Callback callback = new Callback("预授权撤销", backStr, new Date());
			callbackService.saveOrUpdate(callback);
			String resp_code = XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd = XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if ("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)) {// 预授权划拨成功
				 result = cancelService.updateTenderUser(borrowId, tenderVo);
			}
		} catch (Exception e) {
			return false;
		}
		return result;
	}
}
